package cn.edu.cug.cs.gtl.plugins.h3dfile;

import cn.edu.cug.cs.gtl.api.wrapper.ProjectWrapper;
import cn.edu.cug.cs.gtl.apis.render.nodes.Node;
import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.actions.AbstractAction;
import cn.edu.cug.cs.gtl.protos.Layer;
import cn.edu.cug.cs.gtl.protos.Map;
import cn.edu.cug.cs.gtl.protos.Project;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;

public class OpenH3DFileAction extends AbstractAction {


    @Override
    public void initialize(AbstractApplication theApp) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("h3dfile_resource", Locale.getDefault());

        name=resourceBundle.getString("menu.file.open_h3d_file");
        menuItem.setText(name);
        //button.setText(name);
        //button.setToolTipText(name);


        this.theApp = theApp;
        menuItem.addActionListener(this);
        //button.addActionListener(this);
        theApp.getMainFrame().getFileMenu().add(menuItem);
        //theApp.getMainFrame().getFileToolBar().add(button);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        final FileFilter h3dFileFilter = new H3DFileFilter();

        final JFileChooser h3dFileChooser = new JFileChooser(new File(System.getProperty("user.home")));
        h3dFileChooser.setFileFilter(h3dFileFilter);
        h3dFileChooser.removeChoosableFileFilter(h3dFileChooser.getAcceptAllFileFilter());

        if ( h3dFileChooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION )
            return;
        String fileName = h3dFileChooser.getSelectedFile().getAbsolutePath();

        try {
            Project project = ProjectWrapper.readH3DFile(fileName);
            theApp.asModellerApp().getModel3dUIApp().refreshAll(project);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
//
//
//        Node node = null;
//        try {
//            node = theApp.getRender().readSceneGraph(fileName);
//            theApp.setProject(theApp.getRender().getProject());
//            Map map = theApp.getProject().getMap(0);
//            if(map!=null) {
//                theApp.setCurrentMap(map);
//                Layer layer = map.getLayer(0);
//                if(layer!=null)
//                    theApp.setCurrentLayer(layer);
//            }
//        }
//        catch (IOException exception){
//            exception.printStackTrace();
//        }
//        if(node==null) return;
//
//
//        theApp.getMainFrame().getRenderPanel().reset(node);
//        theApp.getMainFrame().getProjectPanel().reset(theApp.getProject());
//        theApp.getMainFrame().getTablePanel().reset();
        return;
    }
}
